import { createRouter, createWebHistory } from 'vue-router'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue'),
    meta: { title: '登录' }
  },
  {
    path: '/',
    component: () => import('../layout/Layout.vue'),
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('../views/Dashboard.vue'),
        meta: { title: '首页', icon: 'HomeFilled' }
      },
      {
        path: 'book',
        name: 'Book',
        component: () => import('../views/book/BookList.vue'),
        meta: { title: '图书管理', icon: 'Reading' }
      },
      {
        path: 'book/add',
        name: 'BookAdd',
        component: () => import('../views/book/BookForm.vue'),
        meta: { title: '添加图书', activeMenu: '/book' }
      },
      {
        path: 'book/edit/:id',
        name: 'BookEdit',
        component: () => import('../views/book/BookForm.vue'),
        meta: { title: '编辑图书', activeMenu: '/book' },
        props: true
      },
      {
        path: 'category',
        name: 'Category',
        component: () => import('../views/category/CategoryList.vue'),
        meta: { title: '分类管理', icon: 'Files' }
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('../views/404.vue')
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - 图书管理系统` : '图书管理系统'
  
  // 判断是否需要登录
  const token = localStorage.getItem('token')
  if (to.path !== '/login' && !token) {
    next('/login')
  } else {
    next()
  }
})

export default router